<template>
  <div class="">
    <!-- Cron生成器 -->
    <el-row class="cron">
      <el-col :span="24" class="mb-10">
        <el-input v-model="inputText">
          <el-button slot="append" @click="clickHandle" size="mini">{{isShow ? '隐藏生成器' : '显示生成器'}}</el-button>
        </el-input>
      </el-col>
      <el-col :span="24" v-show="false">
        <el-row>
          <el-col :span="4">
            <el-select v-model="selectValue" placeholder="*" :size="'mini'" class="mr-10">
              <el-option v-for="item in option" :key="item.value" :label="item.name" :value="item.value"> </el-option>
            </el-select>
          </el-col>
          <el-col :span="16">
            <template v-if="selectValue == 'seconds' || selectValue == 'minutes'">
              <el-select v-model="secondStep" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
              {{ selectValue == 'seconds' ? '秒' : '分钟' }}
            </template>
            <template v-if="selectValue == 'hours'">
              <el-select v-model="hValue" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                <el-option v-for="item in hOptions" :key="item" :label="item" :value="item"> </el-option>
              </el-select>小时
            </template>
            <template v-if="selectValue == 'days'">
              <div class="inline-block">
                每<el-select v-model="daysValues[0]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in hOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>时
              </div>
              <div class="inline-block">
                每<el-select v-model="daysValues[1]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>分
              </div>
              <div class="inline-block">
                每<el-select v-model="daysValues[2]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>秒
              </div>
            </template>
            <template v-if="selectValue == 'weeks'">
              <div class="inline-block">
                每周<el-select v-model="weeksValues[0]" multiple clearable collapse-tags placeholder="*" :size="'mini'">
                  <el-option v-for="item in wOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>
              </div>
              <div class="inline-block">
                每<el-select v-model="weeksValues[1]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in hOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>时
              </div>
              <div class="inline-block">
                每<el-select v-model="weeksValues[2]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>分
              </div>
              <div class="inline-block">
                每<el-select v-model="weeksValues[3]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>秒
              </div>
            </template>
            <template v-if="selectValue == 'months'">
              <div class="inline-block">
                每<el-select v-model="monthsValues[0]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in mOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>月
              </div>
              <div class="inline-block">
                <el-select v-model="monthsCheck" placeholder="*" :size="'mini'" @change="monthsValues[1] = []">
                  <el-option v-for="item in monthsOptions" :key="item.label" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div class="inline-block" v-if="monthsCheck">
                周<el-select v-model="monthsValues[1]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in wOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>
              </div>
              <div class="inline-block" v-else>
                <el-select v-model="monthsValues[1]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in dOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>日
              </div>
              <div class="inline-block">
                每<el-select v-model="monthsValues[2]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in hOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>时
              </div>
              <div class="inline-block">
                每<el-select v-model="monthsValues[3]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>分
              </div>
              <div class="inline-block">
                每<el-select v-model="monthsValues[4]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>秒
              </div>
            </template>
            <template v-if="selectValue == 'years'">
              <div class="inline-block">
                每<el-select v-model="yearsValues[0]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in yOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>年
              </div>
              <div class="inline-block">
                每<el-select v-model="yearsValues[1]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in mOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>月
              </div>
              <div class="inline-block">
                <el-select v-model="monthsCheck" placeholder="*" :size="'mini'" @change="yearsValues[2] = []">
                  <el-option v-for="item in monthsOptions" :key="item.label" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div class="inline-block" v-if="monthsCheck">
                周<el-select v-model="yearsValues[2]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in wOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>
              </div>
              <div class="inline-block" v-else>
                <el-select v-model="yearsValues[2]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in dOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>日
              </div>
              <div class="inline-block">
                每<el-select v-model="yearsValues[3]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in hOptions" :key="item" :label="item" :value="item"> </el-option>
                </el-select>时
              </div>
              <div class="inline-block">
                每<el-select v-model="yearsValues[4]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>分
              </div>
              <div class="inline-block">
                每<el-select v-model="yearsValues[5]" multiple collapse-tags clearable placeholder="*" :size="'mini'">
                  <el-option v-for="item in sOmOptions" :key="item" :label="item" :value="item">
                  </el-option>
                </el-select>秒
              </div>
            </template>
          </el-col>
          <el-col :span="2" :offset="1">
            <el-button type="primary" size="mini" @click="createCron">生成Cron</el-button>
          </el-col>
        </el-row>
        <div>注:不选择则为通配符*,产生的cron将以固定时间为准，若想以几秒/几分钟/几小时/.. 则需全部选择！（待优化）</div>
      </el-col>
    </el-row>

    <el-dialog title="Cron表达式生成器" :visible.sync="isShow" append-to-body :close-on-click-modal="false">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane v-for="(item, index) in configList" :key="item.name" :name="item.name">
          <div slot="label" class="flex-col flex-center flex-col-center mb-10">
            <div>{{item.label}}</div>
            <div style="height:28px;line-height:28px;" class="pl-15 pr-15 radius-6"
              :style="{color:activeName == item.name?'#fff':'#000',background:activeName == item.name?'#409eff':'#ecf5ff'}">
              {{configSrcList[index == configList.length-1 ? configSrcList.length-1 : index]}}</div>
          </div>
          <cron-son ref="cronSon" :name="item.label" :defaultConfig="item.defaultConfig" @change="CronChange">
          </cron-son>
        </el-tab-pane>
      </el-tabs>

      <!-- <el-row class="mb-10">
        <el-col :span="24">
          <el-input v-model="configSrc" disabled class="mb-10"></el-input>
          <el-button type="primary" @click="getCronNumer">测试</el-button>
        </el-col>
      </el-row> -->
      <!-- <div class="p-10 bg-gray radius-5">
        <template v-if="testList.length == 0">
          请增加匹配项
        </template>
        <template v-else>
          <div v-for="item in testList" :key="item">{{item}}</div>
        </template>
      </div> -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="generate">生 成</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CronSon from './CronSon'
export default {
  name: 'cron',
  components: {
    CronSon,
  },
  props: {
    value: String,
  },
  watch: {
    value: {
      immediate: true,
      handler(n, o) {
        if (n != o) {
          this.inputText = n
        }
      },
    },
    inputText: {
      handler(n, o) {
        if (n != o) this.$emit('update:value', this.inputText)
      },
    },
  },
  computed: {
    sOmOptions: () => {
      let arr = []
      for (let i = 0; i <= 59; i++) {
        arr.push(i)
      }
      return arr
    },
    hOptions: () => {
      let arr = []
      for (let i = 0; i <= 23; i++) {
        arr.push(i)
      }
      return arr
    },
    dOptions: () => {
      let arr = []
      for (let i = 1; i <= 31; i++) {
        arr.push(i)
      }
      return arr
    },
    wOptions: () => {
      let arr = []
      for (let i = 1; i <= 7; i++) {
        arr.push(i)
      }
      return arr
    },
    mOptions: () => {
      let arr = []
      for (let i = 1; i <= 12; i++) {
        arr.push(i)
      }
      return arr
    },
    yOptions: () => {
      let date = new Date().getFullYear()
      let arr = []
      for (let i = date; i <= date + 100; i++) {
        arr.push(i)
      }
      return arr
    },
  },
  data() {
    return {
      configList: [
        { label: '秒', name: 'tab1', defaultConfig: { key: 'default,cycle,SE,appoint' } },
        { label: '分', name: 'tab2', defaultConfig: { key: 'default,cycle,SE,appoint' } },
        { label: '时', name: 'tab3', defaultConfig: { key: 'default,cycle,SE,appoint' } },
        { label: '天', name: 'tab4', defaultConfig: { key: 'default,cycle,SE,appoint' } },
        { label: '月', name: 'tab5', defaultConfig: { key: 'default,cycle,SE,appoint' } },
        { label: '年', name: 'tab6', defaultConfig: { key: 'default,year' } },
      ],
      testList: [],
      configSrc: '',
      configSrcList: ['*', '*', '*', '*', '*', '?', '*'],
      activeName: 'tab1',
      isShow: false,
      inputText: '',
      selectValue: 'seconds',
      secondStep: [],
      hValue: [],
      daysValues: [[], [], []],
      weeksValues: [[], [], [], []],
      monthsValues: [[], [], [], [], []],
      monthsCheck: true,
      monthsOptions: [
        { label: '每周', value: true },
        { label: '每日', value: false },
      ],
      yearsValues: [[], [], [], [], [], []],
      // options
      option: [
        { name: '周期/固定秒', value: 'seconds' },
        { name: '周期/固定分', value: 'minutes' },
        { name: '周期/固定小时', value: 'hours' },
        // { name: 'N日', value: 'Ndays' },
        { name: '周期/固定天', value: 'days' },
        { name: '周期/固定周', value: 'weeks' },
        { name: '周期/固定月', value: 'months' },
        { name: '周期/固定年', value: 'years' },
      ],
    }
  },
  methods: {
    createCron() {
      let str = ''
      if (this.selectValue == 'seconds') {
        str = this.checkIsContinuous(this.secondStep) + ' * * * * ? *'
      } else if (this.selectValue == 'minutes') {
        str = '0 ' + this.checkIsContinuous(this.secondStep) + ' * * * ? *'
      } else if (this.selectValue == 'hours') {
        str = '0 0 ' + this.checkIsContinuous(this.hValue) + ' * * ? *'
      } else if (this.selectValue == 'days') {
        str = `${this.checkIsContinuous(this.daysValues[2])} ${this.checkIsContinuous(
          this.daysValues[1],
        )} ${this.checkIsContinuous(this.daysValues[0])} * * ? *`
      } else if (this.selectValue == 'weeks') {
        // 0 0 0 ? * 1 *
        str = `${this.checkIsContinuous(this.weeksValues[3])} ${this.checkIsContinuous(
          this.weeksValues[2],
        )} ${this.checkIsContinuous(this.weeksValues[1])} ? * ${this.checkIsContinuous(this.weeksValues[0])} *`
      } else if (this.selectValue == 'months') {
        if (this.monthsCheck) {
          str = `${this.checkIsContinuous(this.monthsValues[4])} ${this.checkIsContinuous(
            this.monthsValues[3],
          )} ${this.checkIsContinuous(this.monthsValues[2])} ? ${this.checkIsContinuous(
            this.monthsValues[0],
          )} ${this.checkIsContinuous(this.monthsValues[1])} *`
        } else {
          str = `${this.checkIsContinuous(this.monthsValues[4])} ${this.checkIsContinuous(
            this.monthsValues[3],
          )} ${this.checkIsContinuous(this.monthsValues[2])} ${this.checkIsContinuous(
            this.monthsValues[1],
          )} ${this.checkIsContinuous(this.monthsValues[0])} ? *`
        }
      } else if (this.selectValue == 'years') {
        if (this.monthsCheck) {
          str = `${this.checkIsContinuous(this.yearsValues[5])} ${this.checkIsContinuous(
            this.yearsValues[4],
          )} ${this.checkIsContinuous(this.yearsValues[3])} ? ${this.checkIsContinuous(
            this.yearsValues[1],
          )} ${this.checkIsContinuous(this.yearsValues[2])} * ${this.checkIsContinuous(this.yearsValues[0])}`
        } else {
          str = `${this.checkIsContinuous(this.yearsValues[5])} ${this.checkIsContinuous(
            this.yearsValues[4],
          )} ${this.checkIsContinuous(this.yearsValues[3])} ${this.checkIsContinuous(
            this.yearsValues[1],
          )} ${this.checkIsContinuous(this.yearsValues[2])} * ${this.checkIsContinuous(this.yearsValues[0])}`
        }
      }
      this.inputText = str
    },
    clickHandle() {
      this.isShow = !this.isShow
      this.setCronNumber()
    },
    // checkIsContinuous
    checkIsContinuous(arr, bool) {
      if (arr && arr.length != 0) {
        arr = arr.sort((a, b) => a - b)
        if (arr.length == 1) {
          return `${arr[0]}`
        } else {
          if (arr[0] + arr.length - 1 == arr[arr.length - 1]) {
            return `${arr[0]}-${arr[arr.length - 1]}`
          } else {
            return arr.join(',')
          }
        }
      } else {
        return '*'
      }
    },
    handleClick(tab, event) {},
    // 处理子组件数据
    CronChange({ index, value, keyname }) {
      this.configSrcList.splice(index, 1, value)
      this.configSrc = this.configSrcList.join(' ')
    },
    getCronNumer() {
      this.$nextTick(() => {
        this.$refs.cronSon.map((el) => el.dealWithDate())
      })
    },
    setCronNumber() {
      this.$nextTick(() => {
        let arr = this.inputText.split(' ')
        if (arr.length == 6) arr.push('*')
        this.$refs.cronSon.forEach((el, i) => {
          if (i == this.$refs.cronSon.length - 1) i++
          el.defaultDealWithDate(i, arr[i])
        })
      })
    },
    generate() {
      this.getCronNumer()
      setTimeout(() => {
        this.isShow = false
        this.inputText = this.configSrc
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.inline-block {
  margin-right: 10px;
  letter-spacing: 3px;
}
.cron :deep(.el-select .el-input__inner) {
  max-width: 160px;
}
:deep(.el-tabs__item) {
  height: auto;
  line-height: normal;
}
</style>